package com.vimi8.ebb.auth.manage;

import com.vimi8.ebb.auth.model.DBClientDetails;
import com.vimi8.ebb.auth.model.OrganizationDept;
import com.vimi8.ebb.auth.model.RegUser;
import com.vimi8.ebb.auth.service.DBClientDetailsService;
import com.vimi8.ebb.auth.service.GeoCodingsService;
import com.vimi8.ebb.auth.service.OrganizationService;
import com.vimi8.ebb.auth.service.UserAuthorityService;
import com.vimi8.ebb.auth.model.OrganizationEmp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by think on 2016/12/2.
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TestTransactionManageImpl implements TestTransactionManage {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    UserAuthorityService userAuthorityService;
    @Autowired
    private DBClientDetailsService dbClientDetailsService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private GeoCodingsService geoCodingsService;

    @Override
    public Integer userRegister(RegUser regUser) throws Exception {
                int count = 0;
                int isCreatUser=0;
                //存在ClientId,用户想加入该组织
                for (String clientId : regUser.getApplyClientId()) {
                    DBClientDetails clientDetails = null;
                    OrganizationDept organizationDept=null;
                    clientDetails = dbClientDetailsService.getClientDetailsByClientId(clientId);
                    logger.info("register user clientDetails is "+clientDetails);
                    if(clientDetails==null) {
                        continue; //当前clientId 无效,继续循环下一个
                    }
                    //加入 指定的部门
                    if(!StringUtils.isEmpty(regUser.getApplyDeptId())){
                        organizationDept=userAuthorityService.getOrganizationDept(clientId,regUser.getApplyDeptId());
                    }
                    //部门不存在,则加入默认部门deptId="0"
                    if(organizationDept==null) {
                        organizationDept=userAuthorityService.getOrganizationDept(clientId,"0");
                        if(organizationDept==null){
                            continue; //默认部门deptId="0" 无效,继续循环下一个
                        }
                    }
                    //clientId 和 deptId正常,且未创建用户
                    if(isCreatUser<=0){
                        //只执行一次,创建用户
                        try {
                            isCreatUser = userAuthorityService.insertOauthUser(regUser);
                            count+=isCreatUser;
                        } catch (Exception e) {
                            throw new Exception(e.getMessage());
                        }
                    }
                    //logger.warn("clientDetails:"+clientDetails);
                    if (clientDetails.getAllowUsersToJoin()==null || !clientDetails.getAllowUsersToJoin()) {
                        //需要审核才能成为client域下的用户,则把申请记录到表里
                        count += userAuthorityService.insertUserApplyClient(regUser.getUserId(),clientId,organizationDept.getDeptId());
                    }else {
                        //根据clientId给用户配置自动资源
                        LinkedHashSet<String> resourcesSet=new LinkedHashSet();
                        //String resources = "default_resources";
                        if (!StringUtils.isEmpty(clientDetails.getAutoResources())) {
                            resourcesSet.addAll(Arrays.asList(clientDetails.getAutoResources().split("\\|"))) ;
                            //resources = clientDetails.getAutoResources();
                        }
                        //参考 部门,添加部门资源
                        if (!StringUtils.isEmpty(organizationDept.getDeptResources())) {
                            resourcesSet.addAll(Arrays.asList(organizationDept.getDeptResources().split("\\|"))) ;
                            //resources = clientDetails.getAutoResources();
                        }
                        if(resourcesSet.size()==0){
                            resourcesSet.add("default_resources");
                        }

                        //根据clientId给用户配置自动权限
                        LinkedHashSet<String> scopesSet=new LinkedHashSet();
                        //String scopes = "default_scopes";
                        if (!StringUtils.isEmpty(clientDetails.getAutoScopes())) {
                            scopesSet.addAll(Arrays.asList(clientDetails.getAutoScopes().split("\\|"))) ;
                            //scopes = clientDetails.getAutoScopes();
                        }
                        //参考 部门,添加部门权限
                        if (!StringUtils.isEmpty(organizationDept.getDeptScopes ())) {
                            scopesSet.addAll(Arrays.asList(organizationDept.getDeptScopes().split("\\|"))) ;
                            //resources = clientDetails.getAutoResources();
                        }
                        if(scopesSet.size()==0){
                            scopesSet.add("default_scopes");
                        }

                        //查询applyOpenid是否存在,不存在则可使用该applyOpenid
                        String openid = UUID.randomUUID().toString();
                        if (!StringUtils.isEmpty(regUser.getApplyOpenid()) && userAuthorityService.getOpenIdCount(clientId, regUser.getApplyOpenid()) <= 0) {
                            openid = regUser.getApplyOpenid();
                        }
                        //用户插入组织(client域)
                        //数据库，需保证resources,scopes  NOT NULL（已加约束），所以此处resources,scopes不能为null
                        //logger.warn("clientId:"+clientId+",UserId:"+regUser.getUserId()+",openid:"+openid+",resources:"+resources+",scopes:"+scopes);
                        count += userAuthorityService.insertOpenid(clientId, regUser.getUserId(), openid,  String.join("|", resourcesSet), String.join("|", scopesSet));
                        //插入部门
                        logger.info("register user count is "+count);
                        count +=userAuthorityService.insertOrganizationEmp(new OrganizationEmp().clientId("personal").deptId(organizationDept.getDeptId()).userId("111-0217-ccedea46-a1dc-49cf-aac6-688da5526564"));
                        logger.info("register user2 count is "+count);
                    }
                    //申请手动配置的资源,则把申请记录到表里
                    if (regUser.getApplyResources() != null && regUser.getApplyResources().size() > 0 && !StringUtils.isEmpty(clientDetails.getManuResources())) {
                        List<String> manuResources= Arrays.asList(clientDetails.getManuResources().split("\\|"));
                        for (String resourceId : manuResources) {
                            if (regUser.getApplyResources().contains(resourceId)) {
                                count += userAuthorityService.insertUserApplyClientResource(regUser.getUserId(), clientId, resourceId);
                            }
                        }
                    }
                    //申请手动配置的权限,则把申请记录到表里
                    if (regUser.getApplyScopes() != null && regUser.getApplyScopes().size() > 0 && !StringUtils.isEmpty(clientDetails.getManuScopes())) {
                        List<String> manuScopes = Arrays.asList(clientDetails.getManuScopes().split("\\|"));
                        for (String scope : manuScopes) {
                            if (regUser.getApplyScopes().contains(scope)) {
                                count += userAuthorityService.insertUserApplyClientScope(regUser.getUserId(), clientId, scope);
                            }
                        }
                    }

                }
        return count;
    }
}
